//
//  LFLoopView.swift
//  ImageLoopDemo
//
//  Created by 夏灵烽 on 2025/1/7.
//

import UIKit

class LFLoopView: UIView {
    

    let cellId = "LFLoopViewCellId"
    
    var collectionView: UICollectionView?
    var titleLabel: UILabel?
    var pageControl: UIPageControl?
    var titleArray  = [String]()
    var imageArray = [String]()
    
    var timer: Timer?
    
    //MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
        
        setupViewsLayout()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
        setupViews()
        
        setupViewsLayout()
    }
    
    //MARK: - 系统自动布局方法
    override func layoutSubviews() {
        super.layoutSubviews()
        
        setupViewsLayout()
    }
    
    //MARK: - 析构方法
    deinit {
        print("LFLoopView deinit")
        removeTimer()
    }
}

//MARK: - 添加界面视图

extension LFLoopView {
    //MARK: - 添加视图
    func setupViews()  {
        addCollectionView()
        addTitleLabel()
        addPageControl()
    }
    
    //MARK: - 添加CollectionView视图
    func addCollectionView() {
        if collectionView == nil {
            collectionView = UICollectionView(frame: bounds, collectionViewLayout: LFLoopViewLayout())
            collectionView?.register(LFLoopViewCell.self, forCellWithReuseIdentifier: cellId)
            addSubview(collectionView ?? UIView())
            collectionView?.backgroundColor = .clear
            collectionView?.delegate = self
            collectionView?.dataSource = self
            
            DispatchQueue.main.async {
                self.collectionView?.scrollToItem(at: IndexPath(row: 1, section: 0), at: .left, animated: false)
                
                self.addTimer()
            }
        }
        
    }
    
    //MARK: - 添加标题视图
    func addTitleLabel() {
        if titleLabel == nil {
            titleLabel = UILabel()
            titleLabel?.backgroundColor = .clear
            titleLabel?.font = UIFont.systemFont(ofSize: 16)
            titleLabel?.textColor = .darkGray
            insertSubview(titleLabel ?? UILabel(), aboveSubview: collectionView ?? UIView())
        }
    }
    
    //MARK: - 添加分页视图
    func addPageControl() {
        if pageControl == nil {
            pageControl = UIPageControl()
            
            pageControl?.backgroundColor = .clear
            pageControl?.currentPage = 0
            pageControl?.pageIndicatorTintColor = .lightGray
            pageControl?.currentPageIndicatorTintColor = .white
            insertSubview(pageControl ?? UIPageControl(), aboveSubview: collectionView ?? UIView())
            pageControl?.addTarget(self, action: #selector(clickPageChange), for: .valueChanged)
        }
    }
}

//MARK: - 设置视图信息

extension LFLoopView {
    //MARK: - 设置视图信息
    func setViewInfo(titleArray: Array<String>, imageArray: Array<String>)  {
        self.titleArray = titleArray
        self.imageArray = imageArray
        
        if self.titleArray.count >= 1 {
            titleLabel?.text = self.titleArray[0]
        }
        if self.imageArray.count >= 0 {
            pageControl?.numberOfPages = self.imageArray.count
            pageControl?.sizeToFit()
        }
    }
}

//MARK: - 添加视图自动布局

extension LFLoopView {
    
    //MARK: - 添加视图布局
    func setupViewsLayout()  {
        if collectionView != nil {
            collectionView?.translatesAutoresizingMaskIntoConstraints = false
            
            addConstraint(NSLayoutConstraint(item: collectionView!,
                                             attribute: .top,
                                             relatedBy: .equal,
                                             toItem: self,
                                             attribute: .top,
                                             multiplier: 1.0,
                                             constant: 0))
            
            addConstraint(NSLayoutConstraint(item: collectionView!,
                                             attribute: .left,
                                             relatedBy: .equal,
                                             toItem: self,
                                             attribute: .left,
                                             multiplier: 1.0,
                                             constant: 0))
            
            addConstraint(NSLayoutConstraint(item: collectionView!,
                                             attribute: .bottom,
                                             relatedBy: .equal,
                                             toItem: self,
                                             attribute: .bottom,
                                             multiplier: 1.0,
                                             constant: 0))
            
            addConstraint(NSLayoutConstraint(item: collectionView!,
                                             attribute: .right,
                                             relatedBy: .equal,
                                             toItem: self,
                                             attribute: .right,
                                             multiplier: 1.0,
                                             constant: 0))
            
        }
        
        if titleLabel != nil {
            titleLabel?.translatesAutoresizingMaskIntoConstraints = false
            
            let leftConstraint = NSLayoutConstraint(item: titleLabel!,
                                                    attribute: .left,
                                                    relatedBy: .equal,
                                                    toItem: self,
                                                    attribute: .left,
                                                    multiplier: 1.0,
                                                    constant: 10)
            
            let bottomConstraint = NSLayoutConstraint(item: titleLabel!,
                                                      attribute: .bottom,
                                                      relatedBy: .equal,
                                                      toItem: self,
                                                      attribute: .bottom,
                                                      multiplier: 1.0,
                                                      constant: -10)
            
            let widthConstraint = NSLayoutConstraint(item: titleLabel!,
                                                     attribute: .width,
                                                     relatedBy: .equal,
                                                     toItem: nil,
                                                     attribute: .notAnAttribute,
                                                     multiplier: 1.0,
                                                     constant: 150)
            
            
            let heightConstraint = NSLayoutConstraint(item: titleLabel!,
                                                      attribute: .height,
                                                      relatedBy: .equal,
                                                      toItem: nil,
                                                      attribute: .notAnAttribute,
                                                      multiplier: 1.0,
                                                      constant: 30)
            
            NSLayoutConstraint.activate([leftConstraint, bottomConstraint, widthConstraint, heightConstraint])
        }
        
        if pageControl != nil {
            pageControl?.translatesAutoresizingMaskIntoConstraints = false
            
            pageControl?.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10).isActive = true
            pageControl?.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 20).isActive = true
            pageControl?.widthAnchor.constraint(equalToConstant: 120).isActive = true
            pageControl?.heightAnchor.constraint(equalToConstant: 30).isActive = true
        }
    }
}

//MARK: - 添加定时器

extension LFLoopView {
    func addTimer() {
        if timer == nil {
            timer = LFWeakTimerObject.scheduledTimer(timeInterval: 3, target: self, selector: #selector(nextImage), userInfo: nil, repeats: true)
            RunLoop.current.add(timer ?? Timer(), forMode: .default)
        }
        
    }
    
    func removeTimer() {
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
    
    
}

//MARK: - 添加oc响应方法

extension LFLoopView {
    @objc func clickPageChange(sender: UIPageControl) 
    {
        let changePage = sender.currentPage
        
        collectionView?.setContentOffset(CGPoint(x: Int(collectionView?.bounds.width ?? self.bounds.width) * (changePage + 1), y: 0), animated: true)
    }
    
    @objc func nextImage() {
        let offsetx = collectionView?.contentOffset.x ?? self.bounds.width
        let page: Int = Int(offsetx / (collectionView?.bounds.width ?? self.bounds.width))
        
        collectionView?.setContentOffset(CGPoint(x: Int(collectionView?.bounds.width ?? self.bounds.width) * (page + 1), y: 0), animated: true)
    }
}

//MARK: - UICollectionViewDataSource

extension LFLoopView: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if imageArray.count <= 0 {
            return 0
        }
        //头尾分别加一张图片
        return imageArray.count + 2
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? LFLoopViewCell
        if cell == nil {
            cell = LFLoopViewCell()
        }
                
        if indexPath.row == 0 {
            // 使用最后一个图片来填充第一个cell
            cell?.urlStr = imageArray[imageArray.count - 1]
        }else if indexPath.row == imageArray.count + 1 {
            // 使用第一个图片来填充最后一个cell
            cell?.urlStr = imageArray[0]
        }else{
            cell?.urlStr = imageArray[indexPath.row - 1]
        }
        
        return cell ?? LFLoopViewCell()
    }
    
}


//MARK: - UIScrollViewDelegate
extension LFLoopView: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView)
    {
        let offsetx = scrollView.contentOffset.x
        var page: Int = Int(offsetx / scrollView.bounds.width)
        
        print(page)
        
        if page == 0 {
            
            //如果是最后一页，偷偷换成第二页
            
            page = imageArray.count - 1
            
            collectionView?.contentOffset = CGPoint(x: Int(collectionView?.bounds.width ?? 0) * page, y: 0)
            
            titleLabel?.text = titleArray[page]
            pageControl?.currentPage = page
        }else if page == ((collectionView?.numberOfItems(inSection: 0) ?? 0) - 1) {
            
            //如果是第一页，偷偷换成倒数第二页
            
            page = 1
            
            collectionView?.contentOffset = CGPoint(x: Int(collectionView?.bounds.width ?? 0) * page, y: 0)
            
            titleLabel?.text = titleArray[0]
            pageControl?.currentPage = 0
        }else{
            
            titleLabel?.text = titleArray[page - 1]
            pageControl?.currentPage = page - 1
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView)
    {
        removeTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)
    {
        addTimer()
    }
    
}
